package com.sky.controller.user;

import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.ShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 缘友一世
 * date 2023/7/24-15:37
 */
@RestController
@RequestMapping("/user/shoppingCart")
@Slf4j
@Api(tags = "C端-购物车接口")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加购物车")
    @CacheEvict(cacheNames = "shoppingCartCache",allEntries = true)
    public Result<String> add(@RequestBody ShoppingCartDTO shoppingCartDTO){
        log.info("添加购物车：{}", shoppingCartDTO);
        shoppingCartService.addShoppingCart(shoppingCartDTO);
        return Result.success();
    }

    /**
     * 查看购物车
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查看购物车")
    @Cacheable(cacheNames = "shoppingCartCache")
    public Result<List<ShoppingCart>> list(){
        List<ShoppingCart> shoppingCarts = shoppingCartService.showShoppingCart();
        return Result.success(shoppingCarts);
    }


    /**
     * 清空购物车商品
     * @return
     */
    @DeleteMapping("/clean")
    @ApiOperation("清空购物车商品")
    @CacheEvict(cacheNames = "shoppingCartCache",allEntries = true)
    public Result<String> clean(){
        shoppingCartService.cleanShoppingCart();
        return Result.success();
    }

    /**
     * 删除购物车物品
     * @param shoppingCartDTO
     * @return
     */
    @CacheEvict(cacheNames = "shoppingCartCache",allEntries = true)
    @PostMapping("/sub")
    @ApiOperation("删除购物车商品")
    @Transactional
    public Result sub(@RequestBody ShoppingCartDTO shoppingCartDTO) {

        int nums = shoppingCartService.getNums(shoppingCartDTO);
        if(nums==1) {
            //执行删除逻辑
            shoppingCartService.delete(shoppingCartDTO);
            return Result.success("删除成功");
        }
        //否则，执行修改将数量-1
        shoppingCartService.subNums(shoppingCartDTO);
        return Result.success("删除成功");
    }
}
